import axios from 'axios';
import store from "../store";
import router from '../router';
import {Message} from 'element-ui';

// 创建axios实例
const service = axios.create({
  baseURL: process.env.BASE_API, // api的base_url
  timeout: 5000,                 // 请求超时时间
  headers: {
    appType: 2
  },
});

// request拦截器
service.interceptors.request.use(
  // request => request,
  request => {
    if (store.getters.token) {  // 判断是否存在token，如果存在的话，则每个http header都加上token
      request.headers.apiEmpToken = `${store.getters.token}`;
    }

    // console.log("拦截request ======= " + request.url);
    // console.log(request);
    return request;
  }, error => {
    console.log(error); // for debug
    Promise.reject(error);
  });

// respone拦截器
service.interceptors.response.use(
  // response => response,
  response => {
    // console.log(response);

    if (response.data && response.data.code === -1) {
      console.log("拦截response登录失效");
      router.push({path: '/logout'});
      return
    }

    return response;
  },
  error => {
    console.log('err' + error);// for debug
    Message.error('网络异常!');
    // router.push({path: '/logout'});
    return Promise.reject(error);
  }
);
export default service;
